<template>
  <div class="content-wraper">
    <el-row class="content">
      <el-col :span="6" class="content-left">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="showDirectoryMange=true;">流程目录管理</el-button>
        <tree-box
          v-model="selectedNode"
          :data="treeData"
          title="流程目录"
        />
      </el-col>
      <el-col :span="18" class="content-right">
        <div class="btns">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addWorkFlow">新增</el-button>
          <el-button type="success" size="mini" icon="el-icon-edit" @click="udateWorkFlow">修改</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="delWorkFlow">删除</el-button>
        </div>
        <div class="detail">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            highlight-current-row
            @current-change="handleCurrentChange"
          >
            <el-table-column
              prop="name"
              label="流程名称"
            >
              <template slot-scope="scope">
                <a class="detail-span" style="text-decoration:underline;" @click="getDetail(scope.row)">{{ scope.row.name }}</a>
              </template>
            </el-table-column>
            <el-table-column
              prop="menu"
              label="绑定菜单"
            />
            <el-table-column
              prop="description"
              label="流程描述"
            />
            <el-table-column
              prop="founderName"
              label="编制人"
            />
            <el-table-column
              prop="createTime"
              label="编制时间"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.createTime| date }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page.sync="pageParams.pageNum"
            @current-change="handlePageChange"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog
      title="流程定义列表"
      :visible.sync="showDefineWorkList"
      width="700px"
      center
    >
      <div class="detail">
        <!-- 流程定义增删改 -->
        <el-button type="primary" size="mini" @click="addDefineWork(0)">新增</el-button>
        <el-button type="success" size="mini" @click="addDefineWork(1)">修改</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="delDefineWork()">删除</el-button>
        <el-table
          :data="defineWorkList"
          border
          style="width: 100%"
          highlight-current-row
          @current-change="handleCurrentChange1"
        >
          <el-table-column
            prop="addWorkflowName"
            label="流程名称"
          />
          <el-table-column
            prop="defineWorkflowName"
            label="流程定义名称"
          />
          <el-table-column
            prop="organizationName"
            label="机构名称"
          />
          <el-table-column
            prop="userName"
            label="用户名称"
          />
          <!-- <el-table-column
            prop="executorName"
            label="编制人"
          /> -->
          <!-- <el-table-column
            prop="createTime"
            label="编制时间"
          /> -->
          <!-- <el-table-column
              prop="address"
              label="最后修订人"
            /> -->
          <!-- <el-table-column
              prop="updateTime"
              label="最后修订时间"
            /> -->
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="modalPageTotal"
        />
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="showDefineWorkList = false">取 消</el-button>
        <el-button type="primary">确 定</el-button>
      </span> -->
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :title="actionType===1?'新增流程':'更新流程'"
      :visible.sync="showAddWork"
      width="700px"
      center
      @close="closeFn"
    >
      <add-flow ref="form" :data="updateWorkFlowObj" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn">取 消</el-button>
        <el-button type="success" icon="el-icon-plus" @click="addWork_Save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="流程目录"
      :visible.sync="showDirectoryMange"
      width="700px"
      center
    >
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="directAdd(0)">同级新增</el-button>
      <el-button type="success" icon="el-icon-plus" size="mini" @click="directAdd(1)">下级新增</el-button>
      <el-button type="danger" icon="el-icon-delete" size="mini" @click="directDel()">删除</el-button>
      <el-table
        :data="treeData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        highlight-current-row
        default-expand-all
        :tree-props="{children: 'nodes', hasChildren: 'hasChildren'}"
        @current-change="handleNodeClick"
      >
        <el-table-column
          prop="name"
          label="目录名称"
        />
      </el-table>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="新增流程目录"
      :visible.sync="showAddFlowDirect"
      width="700px"
      center
    >
      <el-form label-width="150px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="新增类型" :prop="addDirect&&addDirect.directAddType">
              <span>{{ addDirect&&addDirect.directAddType }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="当前流程目录名称" :prop="directCurrentNode&&directCurrentNode.name">
              <span>{{ directCurrentNode&&directCurrentNode.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="流程目录名称" :prop="addDirect.name">
              <el-input v-model="addDirect.name" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddFlowDirect = false">取 消</el-button>
        <el-button type="success" icon="el-icon-plus" @click="add_Direct">确 定</el-button>
      </span>
    </el-dialog>
    <people-manage :show-modal.sync="showCheckChose" @getSelectedRows="getSelectedPeopleRows" />
  </div>
</template>

<script>
import peopleManage from '@/components/TreeModal/peopleManage'
// import TreeBox from '@/components/TreeBox'
import addFlow from './components/addFlow.vue'
import {
  // 流程定义
  // getDefineWorkflowDetail,
  addDefineWorkflow,
  deleteDefineWorkflow,
  updateDefineWorkflow,
  getDefineWorkflowList,
  // 流程目录
  addWorkflowDirectory,
  deleteWorkflowDirectory,
  // getWorkflowDirectoryDetail,
  // getWorkflowDirectoryList,
  getWorkflowDirectoryTree,
  // updateWorkflowDirectory,
  // 新增流程模块
  addAddWorkflow,
  deleteAddWorkflow,
  // getAddWorkflowDetail,
  getAddWorkflowList,
  updateAddWorkflow
} from '@/api/flow'
export default {
  name: 'FlowDefine',
  components: {
    // TreeBox,
    addFlow,
    peopleManage
  },
  data() {
    return {
      pageParams: {
        pageSize: 10,
        pageNum: 1
      },
      directCurrentNode: null,
      showDirectoryMange: false,
      defaultProps: {
        children: 'nodes',
        label: 'name'
      },
      showAddFlowDirect: false,
      addDirect: {},
      treeData: [], // 流程目录
      tableData: [], // 流程表格数据
      showAddWork: false, // 显示新增流程弹窗
      currentRow: null, // 当前表格选中行
      selectedNode: null, // 当前树结构选中行
      updateWorkFlowObj: {}, // 表格单条流程体
      actionType: 1, // 1 新增流程 2更新流程
      defineWorkList: [], // 流程定义列表数据
      currentDefineWork: null, // 表格选中的单条流程定义
      showCheckChose: false, // 选择审批人
      addObj: {}, // 新增流程定义的弹窗
      addObjType: null,
      filterText: '',
      flowDetail: {},
      total: 0,
      modalPageTotal: 0,
      showDefineWorkList: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    selectedNode(newValue) {
      this.getTableList(newValue)
    }
  },

  mounted() {
    this.initTree()
  },
  methods: {
    getSelectedPeopleRows(obj) {
      // 清除上一次缓存
      this.addObj['organizationId'] = null
      this.addObj['organizationName'] = null
      this.addObj['userId'] = null
      this.addObj['userName'] = null
      this.addObj['name'] = null
      // 新增
      if (obj.directCurrentNode) {
        this.addObj['organizationId'] = obj.directCurrentNode.id
        this.addObj['organizationName'] = obj.directCurrentNode.name
      }
      if (obj.selectRow) {
        this.addObj['userId'] = obj.selectRow.id
        this.addObj['userName'] = obj.selectRow.name
      }
      if (obj.name) {
        this.addObj['name'] = obj.name
      }
      if (this.addObjType === 0) {
        this.add_DefineWork(this.addObj) // userName userId
      } else if (this.addObjType === 1) {
        this.update_DefineWork(this.addObj)
      }
    },
    handlePageChange(e) {
      this.pageParams.pageNum = e
      this.getTableList(this.selectedNode)
    },
    // 获取人员列表
    getPersonList(type) {
      this.showCheckChose = true
    },
    // 获取树结构目录
    initTree() {
      getWorkflowDirectoryTree().then(res => {
        const { nodes } = res.data || {}
        this.treeData = nodes || []
      })
    },
    // 流程目录相关
    handleNodeClick(val) {
      this.directCurrentNode = val
    },
    // 同级新增 0  下级新增 1
    directAdd(type) {
      this.addDirect.directAddType = type === 0 ? '同级新增' : '下级新增'
      if (!this.directCurrentNode && this.treeData.length !== 0) {
        this.$message({
          type: 'error',
          message: '请选择一个流程目录!'
        })
        return
      }
      this.showAddFlowDirect = true
    },
    // 删除目录
    directDel() {
      if (!this.directCurrentNode) {
        this.$message({
          type: 'error',
          message: '请选择一个流程目录!'
        })
        return
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del_Direct()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    del_Direct() {
      const params = {
        workflowDirectoryId: this.directCurrentNode.id
      }
      deleteWorkflowDirectory(params).then(res => {
        this.showTipsFn(res, '删除', () => {
          this.showDirectoryMange = false
          this.directCurrentNode = {}
          this.initTree()
        })
      })
    },
    // 确认新增目录
    add_Direct() {
      if (!this.addDirect.name) {
        this.$message({
          type: 'error',
          message: '请输入流程目录!'
        })
        return
      }
      const params = {
        name: this.addDirect.name,
        ...this.directCurrentNode ? {
          parentId: this.addDirect.directAddType === '同级新增' ? this.directCurrentNode.parentId : this.directCurrentNode.id
        } : {
          parentId: null
        }
      }
      addWorkflowDirectory(params).then(res => {
        this.showTipsFn(res, '保存', () => {
          this.showAddFlowDirect = false
          this.showDirectoryMange = false
          this.directCurrentNode = {}
          this.initTree()
        })
      })
    },
    // 获取流程表格数据
    getTableList(data) {
      const { id, name } = data
      if (id) {
        const params = {
          'workflowDirectoryId': id,
          'name': name,
          ...this.pageParams
        }
        getAddWorkflowList(params).then(res => {
          const { data, total } = res.data || {}
          this.tableData = data
          this.total = total - 0
          // if (data && data.length > 0) {
          // }
        })
      }
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    handleCurrentChange1(val) {
      this.currentDefineWork = val
    },
    closeFn() {
      this.showAddWork = false
      this.$refs.form.resetForm()
    },
    addWorkFlow() {
      if (!this.selectedNode) {
        this.$message({
          type: 'error',
          message: '请选择一个流程目录!'
        })
        return
      }
      this.actionType = 1
      this.showAddWork = true
    },
    addWork_Save() {
      this.$refs.form.validateForm(valid => {
        if (valid) {
          const form = this.$refs.form.form
          const { bindMenuList, ...otherObj } = form
          const bindMenu = bindMenuList.join('-')
          const params = {
            ...otherObj,
            menu: bindMenu,
            workflowDirectoryId: this.selectedNode.id,
            ...this.actionType === 2 ? {
              id: this.updateWorkFlowObj.id
            } : {}
          }
          if (this.actionType === 1) {
            addAddWorkflow(params).then(res => {
              this.showTipsFn(res, '保存', () => {
                this.$refs.form.resetForm()
                this.getTableList(this.selectedNode)
                this.showAddWork = false
              })
            })
          } else {
            updateAddWorkflow(params).then(res => {
              this.showTipsFn(res, '保存', () => {
                this.$refs.form.resetForm()
                this.getTableList(this.selectedNode)
                this.showAddWork = false
              })
              // addAddWorkflow(params).then(res => {
              // })
            })
          }
        }
      })
    },
    udateWorkFlow() {
      if (!this.currentRow) {
        this.$message({
          type: 'error',
          message: '请选择一个流程!'
        })
        return
      }
      this.actionType = 2
      this.updateWorkFlowObj = { ...this.currentRow }
      this.showAddWork = true
    },
    delWorkFlow() {
      if (!this.currentRow) {
        this.$message({
          type: 'error',
          message: '请选择一个流程!'
        })
        return
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del_WorkFlow()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    del_WorkFlow() {
      const params = {
        addWorkflowId: this.currentRow.id
      }
      deleteAddWorkflow(params).then(res => {
        this.showTipsFn(res, '删除', () => {
          this.getTableList(this.selectedNode)
        })
        // addAddWorkflow(params).then(res => {
        // })
      })
    },

    getDetail(data) {
      this.defineWorkList = []

      data = data || this.currentRow
      // 查看详情
      const { id, name } = data
      if (id) {
        getDefineWorkflowList({ addWorkflowId: id, name: name, pageNum: 0, pageSize: 10 }).then(res => {
          //
          // if (res.data && res.data.length > 0) {
          //   this.defineWorkList = res.data
          // }
          if (res.code === '0001' && res.data && res.data.data) {
            this.defineWorkList = res.data.data
            this.modalPageTotal = res.data.total - 0
          }
          this.showDefineWorkList = true
        })
      }
    },
    addDefineWork(type) {
      if (type === 1 && !this.currentDefineWork) {
        this.$message({
          type: 'error',
          message: '请选择一个流程定义!'
        })
        return
      }
      this.getPersonList(type)
      this.addObj['addWorkflowId'] = this.currentRow.id
      // this.addObj['name'] = value
      this.addObjType = type
      //
      // addWorkflowId:this.currentRow.id
      // this.$prompt('请输入流程定义名称', '', {
      //   confirmButtonText: '确定并选择审批人',
      //   cancelButtonText: '取消',
      //   inputValue: this.currentDefineWork ? this.currentDefineWork.defineWorkflowName : ''
      // }).then(({ value }) => {
      //   if (!value) {
      //     this.$message({
      //       type: 'error',
      //       message: '请输入流程定义名称！'
      //     })
      //     return
      //   }
      //   this.getPersonList(type)
      //   this.addObj['addWorkflowId'] = this.currentRow.id
      //   this.addObj['name'] = value
      //   this.addObjType = type
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消输入'
      //   })
      // })
    },
    delDefineWork() {
      if (!this.currentDefineWork) {
        this.$message({
          type: 'error',
          message: '请选择一个流程定义!'
        })
        return
      }
      deleteDefineWorkflow({ defineWorkflowId: this.currentDefineWork.defineWorkflowId }).then(res => {
        this.showTipsFn(res, '删除', () => {
          this.getDetail()
        })
      })
    },
    add_DefineWork(params) {
      addDefineWorkflow(params).then(res => {
        this.showTipsFn(res, '保存', () => {
          this.getDetail()
          this.showCheckChose = false
        })
      })
    },
    update_DefineWork(params) {
      params.id = this.currentDefineWork.defineWorkflowId
      updateDefineWorkflow(params).then(res => {
        this.showTipsFn(res, '保存', () => {
          this.getDetail()
          this.showCheckChose = false
        })
      })
    },
    // 新增，修改，删除 提示文案
    showTipsFn(res, type, successFn) {
      const { code, msg } = res
      if (code === '0001') {
        this.$message({
          type: 'success',
          message: `${type}成功!`
        })
        if (successFn) {
          successFn()
        }
      } else {
        this.$message({
          type: 'error',
          message: msg || `${type}失败!`
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content{
  height:100%;
  .content-left,.content-right{
    height: 100%;
  }
  .content-left{
    padding-right: 10px;
    border-right: 1px solid #dedede;
    .el-button{
      margin-bottom: 10px;
    }
  }
  .content-right{
    padding-left: 10px;
    .detail{
      height: calc(100% - 40px);
      margin-top: 10px;
      overflow: auto;
    }
  }
  .tree{
    height: calc(100% - 40px);
    padding-top: 10px;
  }
}
</style>
